﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Coleotrack.Core;
using Coleotrack.Data;
using Coleotrack.Data.Contracts;
using Coleotrack.Service.Contracts;
using NHibernate;
using NHibernate.Linq;

namespace Coleotrack.Service
{
    public abstract class ServiceBase<T> : IDataService<T> where T: Entity
    {
        private readonly INHibernateUnitOfWork unitOfWork;

        protected ServiceBase(INHibernateUnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        public INHibernateUnitOfWork UnitOfWork
        {
            get { return unitOfWork; }
        }

        public T Find(int id)
        {
            return unitOfWork.CurrentSession.Query<T>().Single(e => e.Id == id);
        }

        public IEnumerable<T> All()
        {
            return unitOfWork.CurrentSession.Query<T>().ToList();
        }

        public int Count()
        {
            return unitOfWork.CurrentSession.Query<T>().Count();
        }

        public IQueryable<T> Select()
        {
            return unitOfWork.CurrentSession.Query<T>();
        }

        public void Insert(T entity)
        {
            unitOfWork.CurrentSession.Save(entity);
        }

        public virtual void Delete(T entity)
        {
            unitOfWork.CurrentSession.Delete(entity);
        }


        public void Evict(T entity)
        {
            unitOfWork.CurrentSession.Evict(entity);
        }
    }
}
